package ar.com.ford.it.fullEconomics.view.action;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.CommodityFacade;
import ar.com.ford.it.fullEconomics.facade.CurrencyFacade;
import ar.com.ford.it.fullEconomics.facade.SupplierFacade;
import ar.com.ford.it.fullEconomics.facade.SupplyFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp04Supply;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.struct.OptionCombo;
import ar.com.ford.it.fullEconomics.struct.SupplyStruct;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;
import ar.com.ford.it.fullEconomics.view.form.SupplyForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class SupplyAction extends AbstractBaseAction {

    @Override
    public ActionForward initPage(FordActionMapping mapping,
                                  ActionForm actionForm,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  WebSession webSession, ActionMessages msgs,
                                  ActionMessages warns, ActionMessages errorMsgs) {

        SupplyForm form = (SupplyForm) actionForm;
        form.resetForm();
        CurrencyFacade facadeCurr = (CurrencyFacade) FacadeProvider.getFacade(
                request, CurrencyFacade.class);
        request.getSession().setAttribute("partClassColl",
                generateClassPart(request));

        request.getSession().setAttribute("partClassCollNew",
                generateClassPart(request));
        request.getSession().setAttribute("tvmModeFindColl",
                generateTvmFindModeCol(request));
        form.setClearParametersPanel();
        form.setModePanel("new");
        try {
            request.getSession().setAttribute("economicMeasure",
                    facadeCurr.getAllCurrency());
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
        }
        return mapping.findForward("success");
    }

    private Collection<OptionCombo> generateClassPart(HttpServletRequest request) {
        Collection<OptionCombo> clasPart = new ArrayList<OptionCombo>();
        MessageResources messageResources = (MessageResources) getResources(request);
        clasPart.add(new OptionCombo("F", messageResources
                .getMessage("supply.label.optionCombo.ford")));
        clasPart.add(new OptionCombo("C", messageResources
                .getMessage("supply.label.optionCombo.custom")));
        return clasPart;
    }

    private Collection<OptionCombo> generateTvmFindModeCol(
                                                           HttpServletRequest request) {
        Collection<OptionCombo> clasPart = new ArrayList<OptionCombo>();
        MessageResources messageResources = (MessageResources) getResources(request);
        clasPart.add(new OptionCombo("E", messageResources
                .getMessage("supply.label.optionCombo.empty")));
        clasPart.add(new OptionCombo("L", messageResources
                .getMessage("supply.label.optionCombo.loaded")));
        return clasPart;
    }

    /**
     * Busca el nombre del supplier AJAX
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward searchNameSupplier(FordActionMapping mapping,
                                            ActionForm actionForm,
                                            HttpServletRequest request,
                                            HttpServletResponse response,
                                            WebSession webSession,
                                            ActionMessages msgs,
                                            ActionMessages warns,
                                            ActionMessages errorMsgs) {
        try {
            Collection<Teess01Supplier> resultName;
            SupplierFacade facade = (SupplierFacade) FacadeProvider.getFacade(
                    request, SupplierFacade.class);
            String codeSupplier = (String) request.getParameter("supplierCode");
            String codeSupplierClass = (String) request
                    .getParameter("supplierClass");
            FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                    .getUser();
            resultName = facade.findSupplier(codeSupplierClass, codeSupplier,
                    null, user.getTeesg01Plant());
            response.setContentType("text/plain");
            if (resultName.isEmpty() || codeSupplier.equals("")) {
                response.getWriter().print("No se encontraron resultados");
            } else {
                response.getWriter().print(
                        resultName.iterator().next().getEess01SupplierNameN()
                                .toString());
            }

        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
        } catch (IOException e) {
            ActionMessages am = new ActionMessages();
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Busca el nombre de la pieza AJAX
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward searchNamePart(FordActionMapping mapping,
                                        ActionForm actionForm,
                                        HttpServletRequest request,
                                        HttpServletResponse response,
                                        WebSession webSession,
                                        ActionMessages msgs,
                                        ActionMessages warns,
                                        ActionMessages errorMsgs) {
        try {
            Teesp01Part resultName;
            CommodityFacade facade = (CommodityFacade) FacadeProvider
                    .getFacade(request, CommodityFacade.class);
            String classPart = (String) request.getParameter("partClass");
            String prefijo = (String) request.getParameter("prefijo");
            String base = (String) request.getParameter("base");
            String sufijo = (String) request.getParameter("sufijo");

            FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                    .getUser();
            Teesp01Part partF = new Teesp01Part();
            partF.setEesp01PartClassCodeC(classPart);
            partF.setEesp01PartPrefixCodeC(prefijo);
            partF.setEesp01PartBaseCodeC(base);
            partF.setEesp01PartSuffixCodeC(sufijo);
            partF.setEesp01PlantCodeC(user.getTeesg01Plant());
            resultName = facade.findPartByPk(partF);
            response.setContentType("text/plain");
            if (resultName == null) {
                response.getWriter().print("No se encontraron resultados");
            } else {
                response.getWriter().print(
                        resultName.getEesp01PartDescriptionX());
            }

        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
        } catch (IOException e) {
            ActionMessages am = new ActionMessages();
            e.printStackTrace();
        }
        return null;
    }

    public ActionForward findSupply(FordActionMapping mapping,
                                    ActionForm actionForm,
                                    HttpServletRequest request,
                                    HttpServletResponse response,
                                    WebSession webSession, ActionMessages msgs,
                                    ActionMessages warns,
                                    ActionMessages errorMsgs) {
        SupplyForm form = (SupplyForm) actionForm;
        Teesp04Supply supplyFind = new Teesp04Supply();
        Calendar fechaEfe = null;
        Timestamp auxFecha = null;
        supplyFind.setTeesp01Part(new Teesp01Part());
        Collection<SupplyStruct> resultSupply = null;
        supplyFind.setTeess01Supplier(new Teess01Supplier());
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        @SuppressWarnings("unused")
        SupplyFacade facadeSupply = (SupplyFacade) FacadeProvider.getFacade(
                request, SupplyFacade.class);
        supplyFind.getTeesp01Part().setEesp01PlantCodeC(user.getTeesg01Plant());
        if (!form.getSupplierCodeF().equals("")) {
            supplyFind.getTeess01Supplier().setEess01SupplierCodeC(
                    form.getSupplierCodeF());
        }
        supplyFind.getTeess01Supplier().setEess01SupplierClassCodeC(
                form.getSupplierF());
        supplyFind.getTeesp01Part().setEesp01PartClassCodeC(form.getPartCF());

        if (!form.getPartPreCF().equals(""))
            supplyFind.getTeesp01Part().setEesp01PartPrefixCodeC(
                    form.getPartPreCF());
        if (!form.getPartBaseF().equals(""))
            supplyFind.getTeesp01Part().setEesp01PartBaseCodeC(
                    form.getPartBaseF());
        if (!form.getPartSufixF().equals(""))
            supplyFind.getTeesp01Part().setEesp01PartSuffixCodeC(
                    form.getPartSufixF());

        // Efe Date in Betew
        if (!form.getDateInEffStart().equals("")) {
            fechaEfe = FullEconomicsDateUtil.format(form.getDateInEffStart());
            auxFecha = new Timestamp(fechaEfe.getTimeInMillis());
            // Date Start
            supplyFind.getTeesp01Part().setEesp01PartInDateY(auxFecha);
            // Date Start and
            fechaEfe = FullEconomicsDateUtil.format(form.getDateInEffEnd());
            auxFecha = new Timestamp(fechaEfe.getTimeInMillis());
            supplyFind.setEesp04LastUpdtS(auxFecha);
        }

        if (!form.getDateOutEffStart().equals("")
                && !form.getDateOutEffEnd().equals("")) {
            // Efe Date out Betewwen
            fechaEfe = FullEconomicsDateUtil.format(form.getDateOutEffStart());
            auxFecha = new Timestamp(fechaEfe.getTimeInMillis());
            // Date Out Start
            supplyFind.getTeesp01Part().setEesp01PartOutDateY(auxFecha);
            // Date Out end
            fechaEfe = FullEconomicsDateUtil.format(form.getDateOutEffEnd());
            auxFecha = new Timestamp(fechaEfe.getTimeInMillis());
            supplyFind.getTeess01Supplier().setEess01LastUpdtS(auxFecha);
        }
        if (form.getTvmFindMode().equalsIgnoreCase("E")) {
            supplyFind.setEesp04SupplyTvmAmountA(new BigDecimal(0));
        } else if (form.getTvmFindMode().equalsIgnoreCase("L")) {
            supplyFind.setEesp04SupplyTvmAmountA(new BigDecimal(1));
        }
        try {
            resultSupply = facadeSupply.findSupply(supplyFind);
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
        }
        if (resultSupply.isEmpty()) {
            errorsMessage(request, "message.noResults");
            form.setSupplyS(resultSupply);
        } else {
            form.setSupplyS(resultSupply);
        }
        if ((form.getModePanel().equals("new") || form.getModePanel().equals(
                "edit"))
                && form.getOperation().equals("createUpdate")) {
            form.setClearParametersPanel();
            form.setModePanel("new");
        }

        return mapping.findForward("success");
    }

    public ActionForward createUpdateSupply(FordActionMapping mapping,
                                            ActionForm actionForm,
                                            HttpServletRequest request,
                                            HttpServletResponse response,
                                            WebSession webSession,
                                            ActionMessages msgs,
                                            ActionMessages warns,
                                            ActionMessages errorMsgs) {
        SupplyForm form = (SupplyForm) actionForm;
        Teesp04Supply supply = new Teesp04Supply();
        // Validaciones antes de crear verifico que exista la parte
        Teesp01Part part = form.getTeesp01Part();
        Teess01Supplier supplier = form.getTeess01Supplier();
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        CommodityFacade facadeCommodity = (CommodityFacade) FacadeProvider
                .getFacade(request, CommodityFacade.class);
        SupplyFacade facadeSupply = (SupplyFacade) FacadeProvider.getFacade(
                request, SupplyFacade.class);
        SupplierFacade facadeSupplier = (SupplierFacade) FacadeProvider
                .getFacade(request, SupplierFacade.class);
        part.setEesp01PlantCodeC(user.getTeesg01Plant());
        CurrencyFacade facadeCurrency = (CurrencyFacade) FacadeProvider
                .getFacade(request, CurrencyFacade.class);
        Collection<SupplyStruct> supplyPor = null;
        supplier.setEess01PlantCodeC(user.getTeesg01Plant());
        supply.setEesp04PlantCodeC(user.getTeesg01Plant());

        try {

            BigDecimal sumaShare = new BigDecimal(0.0);
            if (facadeCommodity.findPartByPk(part) != null) {
                supply.setTeesp01Part(facadeCommodity.findPartByPk(part));
            } else {
                errorsMessage(request, "pricing.error.noPart");
                return mapping.findForward("success");
            }
            if (facadeSupplier.getSupplierByPk(supplier) != null) {
                supply.setTeess01Supplier(facadeSupplier
                        .getSupplierByPk(supplier));
            } else {
                errorsMessage(request, "pricing.error.noSupplier");
                return mapping.findForward("success");
            }
            BigDecimal porC = BigDecimal.valueOf(Double.valueOf(form
                    .getProcShereNew()));
            sumaShare = sumaShare.add(porC);

            if (validatePorcen(facadeSupply, supply, sumaShare).doubleValue() < 101) {

                if (form.getModePanel().equals("new")) {
                    if (!form.getCurrencyNew().equals("-1"))
                        supply.setEesp04SupplyTvmCurrencyC(facadeCurrency
                                .findCurrencyByCode(form.getCurrencyNew()));
                    if (!StringUtils.isBlank(form.getValueTVMNew()))
                        supply
                                .setEesp04SupplyTvmAmountA(BigDecimal
                                        .valueOf(Double.valueOf(form
                                                .getValueTVMNew())));
                    supply.setEesp04SupplySharePercentP(porC);

                    if (!facadeSupply.findSupply(supply).isEmpty()) {
                        errorsMessage(request, "supply.error.existeSupply");
                        return mapping.findForward("success");
                    }
                    supply.setEesp04PlantCodeC(user.getTeesg01Plant());
                    facadeSupply.createSupply(supply, user);
                }
                if (form.getModePanel().equals("edit")) {
                    Boolean updateSupplier = false; 
                    if (facadeSupply.getSupplyByPk(form.getSupplySelected()) != null) {
                        supply = form.getSupplySelected();
                        if (!form.getCurrencyNew().equals("-1"))
                            supply.setEesp04SupplyTvmCurrencyC(facadeCurrency
                                    .findCurrencyByCode(form.getCurrencyNew()));
                        if (StringUtils.isBlank(form.getValueTVMNew())) {
                            supply.setEesp04SupplyTvmAmountA(null);
                        } else {
                            supply.setEesp04SupplyTvmAmountA(BigDecimal
                                    .valueOf(Double.valueOf(form
                                            .getValueTVMNew())));
                            updateSupplier = true;
                        }
                        
                        if (supply.getEesp04SupplySharePercentP().compareTo(porC) != 0)
                             {
                        	 	supply.setEesp04SupplySharePercentP(porC);
                        	 	updateSupplier = true; 	
                             }
                          
                            if (updateSupplier) 
                            	 facadeSupply.updateSupply(supply, user);
                        
                    } else {
                        errorsMessage(request, "supply.error.updateDeleted");
                        return mapping.findForward("success");
                    }
                }
            } else {
                errorsMessage(request, "supply.error.supPorc");
                return mapping.findForward("success");
            }
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
        }
        form.setClearParametersPanel();
        form.setModePanel("new");
        return mapping.findForward("success");

    }

    public ActionForward editSelectedSupply(FordActionMapping mapping,
                                            ActionForm actionForm,
                                            HttpServletRequest request,
                                            HttpServletResponse response,
                                            WebSession webSession,
                                            ActionMessages msgs,
                                            ActionMessages warns,
                                            ActionMessages errorMsgs) {

        SupplyForm form = (SupplyForm) actionForm;
        form.setModePanel("edit");
        form.supplyMapped(form.getSelectedRowNum(), "");
        form.setEditParametersPanel();
        return mapping.findForward("success");
    }

    public ActionForward deleteSupply(FordActionMapping mapping,
                                      ActionForm actionForm,
                                      HttpServletRequest request,
                                      HttpServletResponse response,
                                      WebSession webSession,
                                      ActionMessages msgs,
                                      ActionMessages warns,
                                      ActionMessages errorMsgs) {

        SupplyForm form = (SupplyForm) actionForm;
        form.setModePanel("new");
        SupplyFacade facadeSupply = (SupplyFacade) FacadeProvider.getFacade(
                request, SupplyFacade.class);
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        form.supplyMapped(form.getSelectedRowNum(), "");
        try {
            facadeSupply.deletedSupply(form.getSupplySelected(), user);
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am); // Grabar errores
        }
        form.setEditParametersPanel();
        return mapping.findForward("success");
    }

    public ActionForward cleanFind(FordActionMapping mapping,
                                   ActionForm actionForm,
                                   HttpServletRequest request,
                                   HttpServletResponse response,
                                   WebSession webSession, ActionMessages msgs,
                                   ActionMessages warns,
                                   ActionMessages errorMsgs) {

        SupplyForm form = (SupplyForm) actionForm;
        form.resetPanelFind();
        return mapping.findForward("success");
    }

    public ActionForward cleanPanel(FordActionMapping mapping,
                                    ActionForm actionForm,
                                    HttpServletRequest request,
                                    HttpServletResponse response,
                                    WebSession webSession, ActionMessages msgs,
                                    ActionMessages warns,
                                    ActionMessages errorMsgs) {

        SupplyForm form = (SupplyForm) actionForm;
        form.resetPanelCreateUpdate();
        form.setModePanel("new");

        return mapping.findForward("success");
    }

    /**
     * Crea un precio segun la parte
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward goPricingPart(FordActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse response,
                                       WebSession webSession,
                                       ActionMessages msgs,
                                       ActionMessages warns,
                                       ActionMessages errorMsgs) {

        SupplyForm form = (SupplyForm) actionForm;
        form.resetPanelCreateUpdate();
        form.setModePanel("new");
        form.supplyMapped(form.getSelectedRowNum(), "");
        request.setAttribute("partNew", form.getSupplySelected()
                .getTeesp01Part());
        request.setAttribute("supplierNew", form.getSupplySelected()
                .getTeess01Supplier());
        // Identifico que modo de panel voy a mostrar
        List supplySC = (List) form.getSupplyS();
        SupplyStruct ecoS = (SupplyStruct) supplySC.get(Integer.parseInt(form
                .getSelectedRowNum()) - 1);
        if (ecoS.getTeesp05Pricing().getEesp05PriceEffectiveDateY() == null) {
            request.setAttribute("modePanel", "new");
        } else {
            request.setAttribute("modePanel", "edit");
            request.setAttribute("pricingSelected", ecoS.getTeesp05Pricing());
        }
        return mapping.findForward("success");
    }

    /**
     * genera los mensjes de errores
     * 
     * @param request
     * @param errorLabel
     */
    private void errorsMessage(HttpServletRequest request, String errorLabel) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "customMessage", messageResources.getMessage(errorLabel)));
        saveErrors(request, am);
    }

    /**
     * Validaque el porcentaje de la pieza que quiere ingresar no supere el 10
     * porciente correspondiente a la suma de los distintos supply
     * 
     * @param supplyPor
     * @param sumaShare
     * @return
     * @throws FullEconomicsException
     */
    private BigDecimal validatePorcen(SupplyFacade facadeSupply,
                                      Teesp04Supply ObtSupply,
                                      BigDecimal sumaShare)
            throws FullEconomicsException {

        Collection<Teesp04Supply> res = null;
        res = facadeSupply.findAllSupply(ObtSupply);
        String SupplierCode = ObtSupply.getTeess01Supplier()
                .getEess01SupplierCodeC();
        for (Teesp04Supply sup : res) {
            if (!sup.getTeess01Supplier().getEess01SupplierCodeC().toString()
                    .equals(SupplierCode.toString())) {
                sumaShare = sumaShare.add(sup.getEesp04SupplySharePercentP());
            }
        }

        return sumaShare;
    }

    /**
     * Conexion de la pantalla de part a supply se generan los datos para que
     * luego pueda realizar la busqueda
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward goFindByPart(FordActionMapping mapping,
                                      ActionForm actionForm,
                                      HttpServletRequest request,
                                      HttpServletResponse response,
                                      WebSession webSession,
                                      ActionMessages msgs,
                                      ActionMessages warns,
                                      ActionMessages errorMsgs) {

        SupplyForm form = (SupplyForm) actionForm;
        form.resetForm();
        CurrencyFacade facadeCurr = (CurrencyFacade) FacadeProvider.getFacade(
                request, CurrencyFacade.class);
        request.getSession().setAttribute("partClassColl",
                generateClassPart(request));

        request.getSession().setAttribute("partClassCollNew",
                generateClassPart(request));
        form.resetPanelFind();
        form.resetPanelCreateUpdate();
        form.setModePanel("new");
        try {
            request.getSession().setAttribute("economicMeasure",
                    facadeCurr.getAllCurrency());
            Teesp01Part partFind = (Teesp01Part) request
                    .getAttribute("partFind");
            form.setPartF(partFind.getEesp01PartClassCodeC().toString());
            form.setPartPreCF(partFind.getEesp01PartPrefixCodeC().toString());
            form.setPartBaseF(partFind.getEesp01PartBaseCodeC().toString());
            form.setPartSufixF(partFind.getEesp01PartSuffixCodeC().toString());
            form.setSupplierF("-1");
            form.setSupplierCodeF("");
            form.setPartCF(partFind.getEesp01PartClassCodeC().toString());
        } catch (FullEconomicsException e) {
            ActionMessages am = new ActionMessages();
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
        }
        return mapping.findForward("success");
    }

}